const { Controller } = require("egg");

class DeptController extends Controller {
    /**
     * 获取部门列表
     */
    async index() {
        // 获取部门列表
        let res = await this.service.dept.readList();
        this.ctx.body = {
            code: 200,
            data: res,
            message: "请求成功",
        };
    }

    /**
     * 添加部门
     */
    async create() {
        // 获取部门名字
        const { name } = this.ctx.request.body;
        if (!name) {
            this.ctx.body = {
                code: 400,
                message: "部门名称不能为空",
            };
            return;
        }
        // 查询部门名字是否存在
        const dept = await this.ctx.service.dept.findByName(name);
        if (dept) {
            this.ctx.body = {
                code: 403,
                message: "该部门已存在",
            };
            return;
        }
        // 添加该部门
        let res = await this.service.dept.create(name);
        if (res.affectedRows !== 1) {
            this.ctx.body = {
                code: 500,
                message: "添加失败",
            };
            return;
        }
        // 添加成功
        this.ctx.body = {
            code: 201,
            message: "添加成功",
        };
    }
}

module.exports = DeptController;
